/*
 *  Map Manager
 *  Manage interface between Leaflet and ItemManager
 */

function MapManager()
{
	
	// array storing link to item objects
	var items = [];

	// initialazing map
	var tileLayer = L.tileLayer('http://{s}.tile.cloudmade.com/BC9A493B41014CAABB98F0471D759707/997/256/{z}/{x}/{y}.png', {
				maxZoom: 18,
				attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery Â© <a href="http://cloudmade.com">CloudMade</a>'
				});
	
	var registrationLayer = new L.LayerGroup(); // temp marker where you add thing
	var existingLayer = new L.LayerGroup(); // collect all existing markers
	//var markersGroup = new L.MarkerClusterGroup();
	
	// initialize map object
	map = new L.Map('map', {
		// center in Brussels
	    center: new L.LatLng(39.90973623453719, -93.69140625),
	    zoom: 3,
	    layers: [tileLayer, registrationLayer, existingLayer]
		//layers: [tileLayer, registrationLayer, markersGroup]
		});
	
	// localizing the user
	map.locate({setView: true, maxZoom: 16}); // setView: true, shorcut to ask to locate the user

	// display items on map;
	//MapManager.prototype.displayOnMap();
	
	// refresh list on move end
	init_onMoveEnd();
	console.log('map initialized');
	
	this.getCenter = function()
	{
		return map.getCenter();
	};
	
	this.getPrecision = function()
	{
		var distance = 10000;
		switch(map.getZoom())
		{
			case 18: distance=200; break;
			case 17: distance=200; break;
			case 16: distance=500; break;
			case 15: distance=2000; break;
			case 14: distance=8000; break;
			case 13: distance=32000; break;
			case 12: distance=128000; break;
			case 11: distance=512000; break;
			case 10: distance=2048000; break;
			default: distance=10000; break;
		}
		return distance;
	};
	
	this.createCoordinates = function()
	{
		// getting items
		items = ObjectManager.getItems();
		
		for(i in items)
		{
			items[i].latlng = new L.LatLng(items[i].lat,items[i].lng);
		}
	};
	
	this.displayOnMap = function()
	{
		// getting items
		items = ObjectManager.getItems();
		
		// create coordinates
		MapManager.createCoordinates();
		
		// update distance
		updateDistance();
		
		existingLayer.clearLayers();
		//markersGroup.clearLayers(); // cleaning the layer
		
		for(i in items)
		{
			if(items[i].distance < MapManager.getPrecision())
			{
				var markerLocation = new L.LatLng(items[i].lat, items[i].lng);
				var marker = new L.Marker(markerLocation);
				// Message
				var msg = '<div id="thing_popup">'
				+ '<img src="" />'
				+ '<strong>' + items[i].title + '</strong></br>'
				+ items[i].description + '</br>'
				+ 'by ' + items[i].username + '<div/>';
	
				//	items[i].id+" - "+;
	
				
			    marker.bindPopup(msg);
			    
			    //markersGroup.addLayer(marker);
			    existingLayer.addLayer(marker);
			    items[i].setMarker(marker);
			}
		}
		
		//existingLayer.addLayer(markersGroup);
		//ObjectManager.things[0].marker.openPopup(); we can access the object marker through our object thing :)
	};
	
	/*
	 *  Create an object
	 *  
	 */
	
	var registrationMarker = new L.Marker([0,0]);
	
	registrationMarker.options.draggable = true;
	var firstClick = true;
	function onMapClick(e)
	{
		var markerLocation = new L.LatLng(e.latlng.lat, e.latlng.lng);
		registrationMarker.setLatLng(markerLocation);
	    registrationLayer.clearLayers();
	    registrationLayer.addLayer(registrationMarker);	
		var msg = 'Your object will be added here! You can still move it';
				
		registrationMarker.bindPopup(msg, {closeButton: false}).openPopup();
		
		if(firstClick)
		{
			firstClick = false;
			$('#register_area').html('<img class="center" src="assets/img/ajax-loader.gif">');
		    $('#register_area').load('pages/view_part/register');
		}
	}
	
	function updateDistance()
	{
		var mapCenter = map.getCenter();
		// refresh distance in items list
		ObjectManager.refreshDistance(mapCenter);
	}
	
	/*
	 *  Others
	 * 
	 */
	
	function onMoveEnd(e)
	{
		console.log('onMoveEnd');
		
		// create bounds array
		var bounds = [];
		// get map bounds
		bounds[0] = map.getBounds().getNorthWest().lat;
		bounds[1] = map.getBounds().getNorthWest().lng;
		bounds[2] = map.getBounds().getSouthEast().lat;
		bounds[3] = map.getBounds().getSouthEast().lng;
		// get items
		ObjectManager.refresh('bounds', null, bounds);
		
		// refresh distance in items list
		//updateDistance();
	}
	
	function init_onMoveEnd()
	{
		map.addEventListener('moveend', onMoveEnd);
		//map.on('moveend', onMoveEnd);
	}
	
	function cancel_onMoveEnd()
	{
		map.removeEventListener('moveend', onMoveEnd);
	}
	
	this.locate = function(id)
	{
		var items = ObjectManager.getItems();
		latLng = [items[id].lat, items[id].lng];
		map.panTo(latLng);
	};
	
	function location_search(string)
	{
		//alert(string);
		var bounds = map.getBounds();
		NW = bounds.getNorthWest();
		NWlat = bounds.getNorthWest().lat;
		NWlng = bounds.getNorthWest().lng;
		SElat = bounds.getSouthEast().lat;
		SElng = bounds.getSouthEast().lng;
		bounds = new Array(NWlat, NWlng, SElat, SElng);
		
		$.ajax({
			url: 'http://open.mapquestapi.com/geocoding/v1/address',
			dataType: 'jsonp',
			crossDomain: true,
			data: {
				location : string,
				boundingBox: {
					ul:{
						lat:NWlat,
						lng:NWlng},
					lr:{
						lat:SElat,
						lng:SElng}
					},
				maxResults : 1
			},
			timeout: 3000,
			success: function(data)
			{
				lat = data.results[0].locations[0].latLng.lat;
				lng = data.results[0].locations[0].latLng.lng;
				latLng = [lat, lng];
				map.panTo(latLng);
				display_alert('location found', '#alert_area', 'success');
			},
	        error: function() { display_alert('connexion problem', '#alert_area', 'error'); }
		});
	}
};